<?php
/**
 * Created by PhpStorm.
 * User: 共赢岛
 * Date: 2024/1/27
 * Time: 15:19
 */

namespace App\Models;

use App\Services\AliyunSmsService;
use Illuminate\Database\Eloquent\Model;

class SmsLog extends Model
{
    protected $fillable = [
        'type',
        'phone',
        'code',
        'checked',
        'status',
        'reason',
    ];

    //类型(0:短信验证码,1:语音验证码,2:短信消息通知，3：找回密码验证,4:注册验证码)
    const TYPE_CODE = 0;

    //是否验证(0:未验证,1:已验证)
    const CHECKED_UNVERIFIED = 0;
    const CHECKED_VERIFIED = 1;

    //状态(0:未发送,1:已发送,2:发送失败)
    const STATUS_NO_SEND = 0;
    const STATUS_SEND = 1;
    const STATUS_FAIL = 2;

    //短信发送间隔时间，默认60秒
    const SEND_INTERVAL_TIME = 60;

    /**
     * 检测短信验证码
     */
    protected function checkCode($phone, $code)
    {
        if (!$phone) {
            return failureMessage('手机号不能为空!');
        }

        if (!checkMobile($phone)) {
            return failureMessage('手机号不正确!');
        }

        if (!$code) {
            return failureMessage('验证码不能为空!');
        }

        $sms_log = $this->where([
            ['type', self::TYPE_CODE],
            ['phone', $phone],
            ['status', self::STATUS_SEND],
            ['checked', self::CHECKED_UNVERIFIED],
        ])->orderBy('created_at', 'desc')->first();

        if (!$sms_log) {
            return failureMessage('验证码不存在,请重新获取!');
        }

        if ($code != $sms_log->code) {
            return failureMessage('验证码错误!');
        }

        if (time() > strtotime("+5minutes", strtotime($sms_log->created_at))) {
            return failureMessage('手机验证码超时!');
        }

        $sms_log->checked = self::CHECKED_VERIFIED;
        $sms_log->save();

        return successMessage();
    }

    /**
     * 检测短信频率
     */
    public function checkRate($phone)
    {
        if (!$phone) {
            return failureMessage('手机号不能为空!');
        }

        $sms_log = $this->where([
            ['phone', $phone],
            ['status', self::STATUS_SEND],
        ])->orderBy('created_at', 'desc')->first();

        $now = time();

        if ($sms_log) {
            if (($now - strtotime($sms_log->created_at)) < self::SEND_INTERVAL_TIME) {
                return failureMessage('短信发送太频繁,请稍后再试!');
            }
        }

        return true;
    }

    /**
     * 发送短信验证码
     */
    protected function sendVerifyCode($phone, $type = 0)
    {
        self::checkRate($phone);

        $code = mt_rand(1000, 9999);

        $sms_log = $this->create([
            'type' => $type,
            'phone' => $phone,
            'code' => $code,
            'checked' => self::CHECKED_UNVERIFIED,
            'status' => self::STATUS_NO_SEND,
        ]);

        try {
            AliyunSmsService::sendSms($phone, AliyunSmsService::$templateCodes['VERIFICATION_CODE'], ['code' => $code]);

            $sms_log->status = self::STATUS_SEND;
            $sms_log->save();

            return successMessage();
        } catch (\Exception $e) {
            $sms_log->status = self::STATUS_FAIL;
            $sms_log->reason = $e->getMessage();
            $sms_log->save();

            return failureMessage($e->getMessage());
        }
    }
}